package util;


import enums.CommonIntEnum;
import enums.CommonStringEnum;
import exception.AncException;

/**
 * @author xiongyx
 * @date 2019/10/25
 *
 * 枚举工具类
 */
public class CommonEnumUtil {

    /**
     * 通过string类型code 获取枚举
     * */
    public static <T extends CommonStringEnum> T getStringEnumByCode(String code, Class<T> commonStringEnumClass){
        if(code == null){
            return null;
        }

        for (T item : commonStringEnumClass.getEnumConstants()) {
            if(code.equals(item.getCode())){
                return item;
            }
        }
        return null;
    }

    /**
     * 通过string类型code 获取枚举 （没找到匹配项 抛出异常）
     * */
    public static <T extends CommonStringEnum> T getStringEnumByCodeValidate(String code,Class<T> commonStringEnumClass){
        if(code == null){
            throw new AncException("code required");
        }

        for (T item : commonStringEnumClass.getEnumConstants()) {
            if(code.equals(item.getCode())){
                return item;
            }
        }

        throw new AncException("unknown code=" + code);
    }

    /**
     * 通过int类型code 获取枚举
     * */
    public static <T extends CommonIntEnum> T getIntEnumByCode(Integer code, Class<T> commonIntEnumClass){
        if(code == null){
            return null;
        }

        for (T item : commonIntEnumClass.getEnumConstants()) {
            if(code.equals(item.getCode())){
                return item;
            }
        }
        return null;
    }

    /**
     * 通过int类型code 获取枚举
     * */
    public static <T extends CommonIntEnum> T getIntEnumByCodeValidate(Integer code,Class<T> commonIntEnumClass){
        if(code == null){
            throw new AncException("code required");
        }

        for (T item : commonIntEnumClass.getEnumConstants()) {
            if(code.equals(item.getCode())){
                return item;
            }
        }

        throw new AncException("unknown code=" + code);
    }
}
